package com.example.config;

import com.example.pojo.Configuration;
import com.example.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 该类新增insert、delete、update的标签的解析
 * 并把之前按对select标签的解析方法提取出来，封装成通用的解析处理方法mappedStatementHandle（）
 *
 * @author kangshuai
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");
        mappedStatementHandle(selectList, namespace);

        List<Element> insertList = rootElement.selectNodes("//insert");
        mappedStatementHandle(insertList, namespace);

        List<Element> updateList = rootElement.selectNodes("//update");
        mappedStatementHandle(updateList, namespace);

        List<Element> deleteList = rootElement.selectNodes("//delete");
        mappedStatementHandle(deleteList, namespace);
    }

    private void mappedStatementHandle(List<Element> list, String namespace) throws Exception {
        for (Element element : list) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(element.attributeValue("id"));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setSql(element.getTextTrim());
            configuration.getMappedStatementMap().put(namespace + "." + element.attributeValue("id"), mappedStatement);
        }
    }

}
